/*
 * Copyright 2011 Sina.
 *
 * Licensed under the Apache License and Weibo License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.open.weibo.com
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.zt.weibo.login;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.format.Time;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.weibo.net.AccessToken;
import com.zt.weibo.R;
import com.zt.weibo.WeiboApp;
import com.zt.weibo.utils.PrintLog;
import com.zt.weibo.utils.SwitchActivity;
import com.zt.weibo.utils.WeiboCons;

public class LoginActivity extends Activity {
	/** Called when the activity is first created. */
	private Button	mLoginBtn = null;
	private Button	mUserBtn = null;
	private EditText	mInputEdit = null;
	private ListView	mUserList = null;
	private String	mUserName = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.longin_main);
		PrintLog.debug("LoginActivity On Create");
		WeiboApp.addActivity(this);
	}
	
	@Override
	protected void onStart()
	{
		super.onStart();
		PrintLog.debug("LoginActivity On Start");
		PrintLog.debug("intent = " + getIntent().getAction());
		findView();
		initView();
		setListeners();
		mInputEdit.setText("");
	}
	
	@Override
	public void onResume() {
		super.onResume();
		PrintLog.debug("LoginActivity On Resume");
		if (WeiboApp.bIsFirstCreate)
		{
			if (null != WeiboApp.mDBMgr.getAllUsers())
			{
				mUserName = WeiboApp.mDBMgr.getAllUsers().get(0);
				existedUserInit();
			}
		}
		else if (Intent.ACTION_MAIN.equals(getIntent().getAction()))
		{
			SwitchActivity.weiboMain(LoginActivity.this);
		}
	}

	@Override
	protected void onPause()
	{
		super.onPause();
		PrintLog.debug("LoginActivity On Pause");
		WeiboApp.bIsFirstCreate = false;
		getIntent().setAction("");
	}

	@Override
	protected void onStop()
	{
		super.onStop();
		PrintLog.debug("LoginActivity On Stop");
	}

	@Override
	protected void onDestroy()
	{
		super.onDestroy();
		PrintLog.debug("LonginActivity On Destroy");
		WeiboApp.delActivity(this);
	}
	
	private void findView()
	{
		mLoginBtn = (Button) findViewById(R.id.login_btn);
		mUserBtn = (Button) findViewById(R.id.login_changeuser_btn);
		mInputEdit = (EditText) findViewById(R.id.login_input_edittext);
		mUserList = (ListView) findViewById(R.id.login_username_list);
	}
	
	private void initView()
	{
		WeiboApp.mWeibo.setupConsumerConfig(WeiboCons.APP_KEY, WeiboCons.APP_SECRET);
		WeiboApp.mWeibo.setRedirectUrl(WeiboCons.URL_REDIRECT);//设置回调页，和网站填写相同即可，不能为空。
		if(null != WeiboApp.mDBMgr.getAllUsers())
		{
			ArrayAdapter<String> mUserAdapter = new ArrayAdapter<String>(LoginActivity.this,
					R.layout.login_list_item, WeiboApp.mDBMgr.getAllUsers());
			mUserList.setAdapter(mUserAdapter);
		}
	}
	
	private void setListeners()
	{
		mLoginBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v)
			{
				mUserName = mInputEdit.getText().toString().trim();
				if(null == mUserName || "".equals(mUserName))
				{
					Toast.makeText(LoginActivity.this, getString(R.string.toast_no_username), 1000).show();
					return;
				}
				PrintLog.debug("用户名 " + mUserName);
				// Oauth2.0
				// 隐式授权认证方式
				if(WeiboApp.mDBMgr.isUserExist(mUserName))
				{
					existedUserInit();
				}
				else
				{
					PrintLog.debug("用户不存在");
					WeiboApp.bIsUserExist = false;
					WeiboApp.bIsUserInvalid = true;
					AccessToken accessToken = new AccessToken("", WeiboCons.APP_KEY);
					accessToken.setExpiresIn(null);
					WeiboApp.mWeibo.setAccessToken(accessToken);
					startAuthorize();
				}
			}
		});
		
		mUserBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v)
			{
				if(View.GONE == mUserList.getVisibility())
					mUserList.setVisibility(View.VISIBLE);
				else 
					mUserList.setVisibility(View.GONE);
			}
		});
		
		mUserList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
			{
				mInputEdit.setText((String)mUserList.getAdapter().getItem(arg2));
				mInputEdit.setSelection(mInputEdit.length());
			}
		});
	}
	
	/**
	 * 对已经存在的用户进行初始化。
	 */
	private void existedUserInit()
	{
		PrintLog.debug("用户已经存在");
		WeiboApp.bIsUserExist = true;
		int invalidDate = WeiboApp.mDBMgr.queryInvalidDate(mUserName);
		Time time = new Time();
		time.setToNow();
		int nowDate = (int)(time.toMillis(true) / 1000);
		Time invalTime = new Time();
		invalTime.set((long)invalidDate * 1000);
		PrintLog.debug("过期时间 = " + invalTime.format2445() +
				"\n 当前时间 = " + time.format2445());
		if(nowDate >= (invalidDate))
		{
			PrintLog.debug("AccessToken已经过期");
			WeiboApp.bIsUserInvalid = true;
			startAuthorize();
		}
		else
		{
			PrintLog.debug("AccessToken未过期");
			WeiboApp.bIsUserInvalid = false;
			String token = WeiboApp.mDBMgr.queryAccessToken(mUserName);
			String expires_in = WeiboApp.mDBMgr.queryExpiresIn(mUserName);
			if(null == WeiboApp.mWeibo.getAccessToken())
			{
				PrintLog.debug("初次启动，Token对象为空");
				AccessToken accessToken = new AccessToken(token, WeiboCons.APP_KEY);
				accessToken.setExpiresIn(expires_in);
				WeiboApp.mWeibo.setAccessToken(accessToken);
				PrintLog.debug("设置了Token对象");
			}
			else
			{
				WeiboApp.mWeibo.getAccessToken().setToken(token);
				WeiboApp.mWeibo.getAccessToken().setExpiresIn(expires_in);
				PrintLog.debug("更新了Token对象");
			}
			WeiboApp.mDBMgr.moveToFirst(mUserName);
			SwitchActivity.weiboMain(LoginActivity.this);
		}
	}
	
	private void startAuthorize()
	{
		SwitchActivity.auth(LoginActivity.this, mUserName);
	}
	
}